package com.hejing.线程安全问题;

/**
 * ClassName: HappyNewYear
 * Package: com.hejing.线程安全问题
 * Description:
 *      案例: 模拟新年倒计时，每隔一秒输出一个数字，依次输出 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 最后输出，新年快乐.
 *      使用实现接口的方式进行多线程编程，并利用同步代码块的方式解决线程安全问题。
 * @Author: HeJing
 * @Create: 2023-04-14 21:59
 * @Version: 1.0
 */
public class HappyNewYearTest {
    public static void main(String[] args) {

        InputNumber01 i1 = new InputNumber01();

        Thread t1 = new Thread(i1);
        Thread t2 = new Thread(i1);
        Thread t3 = new Thread(i1);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();


    }
}


class InputNumber01 implements Runnable {
    int num = 10;

    @Override
    public void run() {
        while(true) {
            synchronized(InputNumber01.class) {
                try{
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(num > 0) {
                    System.out.println(Thread.currentThread().getName() + ": " + num);
                    num--;
                } else {
                    break;
                }
            }
        }
        System.out.println("新年快乐");
    }
}






















